#pragma once

#include<iostream>
#include<cstring>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string>
#include"Log.hpp"
using namespace LogMod;

class udpserve{
    public:
    udpserve(const int& port)
    :_port(port)
    {
    }

    void init()
    {
        _socketfd = socket(AF_INET,SOCK_DGRAM,0);
        struct sockaddr_in addr;
        memset(&addr,0,sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(_port);      
        addr.sin_addr.s_addr = INADDR_ANY;
        socklen_t size = sizeof(addr);
        if(bind(_socketfd,(struct sockaddr*)&addr,size) < 0)
        {
            LOG(level::FATAL)<<"bind false";
            exit(1);
        }
        LOG(level::INFO)<<"bind success";
        
    }

    void start()
    {
        while(1)
        {
            char buff[512];
            struct sockaddr_in addrin;
            socklen_t sizein = sizeof(addrin);
            ssize_t n = recvfrom(_socketfd,buff,sizeof(buff)-1,0,(struct sockaddr*)&addrin,&sizein);
            if(n > 0)
            {
                buff[n] = 0;
                LOG(level::DEBUG)<<buff;
                
                std::string message;
                message = "server say# ";
                message += buff;
                ssize_t m = sendto(_socketfd,message.c_str(),message.size(),0,(struct sockaddr*)&addrin, sizein);
            }
            
        }
    }

    ~udpserve(){}
    private:
    int _socketfd;
    int _port;
};